package com.aabte.permissionframeworklearn.permission.service;

import com.aabte.permissionframeworklearn.permission.common.RequestHolder;
import com.aabte.permissionframeworklearn.permission.exception.ParamException;
import com.aabte.permissionframeworklearn.permission.mapper.SysRoleAclMapper;
import com.aabte.permissionframeworklearn.permission.mapper.SysRoleMapper;
import com.aabte.permissionframeworklearn.permission.mapper.SysUserMapper;
import com.aabte.permissionframeworklearn.permission.mapper.SysUserRoleMapper;
import com.aabte.permissionframeworklearn.permission.model.SysRole;
import com.aabte.permissionframeworklearn.permission.model.SysUser;
import com.aabte.permissionframeworklearn.permission.param.RoleParam;
import com.aabte.permissionframeworklearn.permission.util.BeanValidator;
import com.aabte.permissionframeworklearn.permission.util.IpUtil;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Daniel
 */
@Service
public class SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleAclMapper sysRoleAclMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysLogService sysLogService;

    public SysRole save(RoleParam param) {
        BeanValidator.check(param);

        if (checkExist(param.getName(), param.getId())) {
            throw new ParamException("角色名称已经存在！");
        }

        SysRole sysRole = SysRole.builder()
                .name(param.getName())
                .type(param.getType())
                .status(param.getStatus())
                .remark(param.getRemake())
                .operator(RequestHolder.getCurrentUser().getUsername())
                .operateIp(IpUtil.getRemoteIpAddress(RequestHolder.getCurrentRequest()))
                .operateTime(new Date())
                .build();

        sysRoleMapper.insertSelective(sysRole);
        sysLogService.saveRoleLog(null, sysRole);
        return sysRole;
    }

    public SysRole update(RoleParam param) {
        BeanValidator.check(param);

        if (checkExist(param.getName(), param.getId())) {
            throw new ParamException("角色名称已经存在！");
        }

        SysRole before = sysRoleMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before, "待更新的角色不存在！");

        SysRole after = SysRole.builder()
                .id(param.getId())
                .name(param.getName())
                .type(param.getType())
                .status(param.getStatus())
                .remark(param.getRemake())
                .operator(RequestHolder.getCurrentUser().getUsername())
                .operateIp(IpUtil.getRemoteIpAddress(RequestHolder.getCurrentRequest()))
                .operateTime(new Date())
                .build();

        sysRoleMapper.updateByPrimaryKeySelective(after);
        sysLogService.saveRoleLog(before, after);
        return after;
    }

    public List<SysRole> getAll() {
        return sysRoleMapper.getAll();
    }

    private boolean checkExist(String name, Long id) {
        return sysRoleMapper.countByRoleNameAndId(name, id) > 1;
    }

    public SysRole delete(Long id) {
        SysRole sysRole = sysRoleMapper.selectByPrimaryKey(id);
        Preconditions.checkNotNull(sysRole, "待删除的角色不存在！");

        boolean isExistUser = sysUserRoleMapper.countByRoleId(id) > 0;
        if (isExistUser) {
            throw new ParamException("待删除的角色有绑定用户，无法删除！");
        }

        boolean isExistAcl = sysRoleAclMapper.countByRoleId(id) > 0;
        if (isExistAcl) {
            throw new ParamException("待删除的角色有绑定权限，无法删除！");
        }

        sysRoleMapper.deleteByPrimaryKey(id);
        return sysRole;
    }

    public List<SysRole> getRoleListByUserId(Long userId) {
        List<Long> roleIds = sysUserRoleMapper.getRoleIdListByUserId(userId);
        if (CollectionUtils.isEmpty(roleIds)) {
            return Lists.newArrayList();
        }
        return sysRoleMapper.getByIdList(roleIds);
    }

    public List<SysRole> getRoleListByAclId(Long aclId) {
        List<Long> roleIds = sysRoleAclMapper.getRoleIdListByAclId(aclId);
        if (CollectionUtils.isEmpty(roleIds)) {
            return Lists.newArrayList();
        }
        return sysRoleMapper.getByIdList(roleIds);
    }

    public List<SysUser> getUserListByRoles(List<SysRole> roles) {
        if (CollectionUtils.isEmpty(roles)) {
            return Lists.newArrayList();
        }
        List<Long> roleIds = roles.stream().map(SysRole::getId).collect(Collectors.toList());

        List<Long> userIds = sysUserRoleMapper.getUserIdListByRoleIdIn(roleIds);

        return sysUserMapper.getByIdList(userIds);
    }
}
